package platformlog_logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"time"
	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddHeartbeatsInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAddHeartbeatsInfoLogic 新增心跳信息
func NewAddHeartbeatsInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddHeartbeatsInfoLogic {
	return &AddHeartbeatsInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddHeartbeatsInfoLogic) AddHeartbeatsInfo(req *types.AddHeartbeatsRequest) (resp *types.AddHeartbeatsResponse, err error) {
	flag := l.svcCtx.Config.UseMysql

	var insertSQL string
	insertSQL = fmt.Sprintf(`
		INSERT INTO %s (cluster_id, agent_id, hostname, ip_address, status, cpu_usage, memory_usage, disk_space, process_count, last_heartbeat)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		ON CONFLICT(hostname, ip_address) DO UPDATE SET
		    cluster_id=excluded.cluster_id,
			status=excluded.status,
			cpu_usage=excluded.cpu_usage,
			memory_usage=excluded.memory_usage,
			disk_space=excluded.disk_space,
			process_count=excluded.process_count,
			last_heartbeat=excluded.last_heartbeat;`, l.svcCtx.Config.SQLite.Tables.AgentHeartbeats)
	if flag {
		insertSQL = fmt.Sprintf(`
		INSERT INTO %s (cluster_id, agent_id, hostname, ip_address, status, cpu_usage, memory_usage, disk_space, process_count, last_heartbeat)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		ON DUPLICATE KEY UPDATE
		    cluster_id=VALUES(cluster_id),
			status=VALUES(status),
			cpu_usage=VALUES(cpu_usage),
			memory_usage=VALUES(memory_usage),
			disk_space=VALUES(disk_space),
			process_count=VALUES(process_count),
			last_heartbeat=VALUES(last_heartbeat);`, l.svcCtx.Config.Mysql.Tables.AgentHeartbeats)
	}

	currentTime := time.Now().Format("2006-01-02 15:04:05.000")
	err = l.svcCtx.Conn.TransactCtx(context.Background(), func(ctx context.Context, sess sqlx.Session) error {
		_, err = sess.ExecCtx(ctx, insertSQL,
			req.HeartbeatInfo.ClusterId,
			req.HeartbeatInfo.AgentId,
			req.HeartbeatInfo.HostName,
			req.HeartbeatInfo.IPAddress,
			req.HeartbeatInfo.Status,
			req.HeartbeatInfo.CPUUsage,
			req.HeartbeatInfo.MemoryUsage,
			req.HeartbeatInfo.DiskSpace,
			req.HeartbeatInfo.ProcessCount,
			currentTime)
		if err != nil {
			logx.Errorf("failed to execute insert: %v", err)
			return err
		}
		return nil
	})

	if err != nil {
		logx.Errorf("failed to add heartbeats info: %v", err)
		return nil, err
	}

	return &types.AddHeartbeatsResponse{
		Code:    200,
		Message: "心跳信息写入完成",
	}, nil
}
